import orm from '@main/db/orm'
import { IpcHandler, IpcInvoke } from '@main/decorator/ipc.decorator'
import { Injectable } from '@nestjs/common'
import type { ModelChat } from '@shared/types/entity'
import { modelChat } from '@shared/constant/schema'
import { and, ilike, eq, inArray } from 'drizzle-orm'

@IpcHandler('modelChat')
@Injectable()
export class ModelChatApi {
  @IpcInvoke('getList')
  async getList(q: ModelChat): Promise<ModelChat[]> {
    return await orm
      .select()
      .from(modelChat)
      .where(and(q.name ? ilike(modelChat.name, q.name) : undefined))
  }

  @IpcInvoke('getPage')
  async getPage(q: ModelChat, pageSize: number, pageNum: number): Promise<ModelChat[]> {
    return await orm
      .select()
      .from(modelChat)
      .where(and(q.name ? ilike(modelChat.name, q.name) : undefined))
      .limit(pageSize)
      .offset(pageSize * pageNum)
  }

  @IpcInvoke('getCount')
  async getCount(q: ModelChat): Promise<number> {
    return await orm.$count(modelChat, and(q.name ? ilike(modelChat.name, q.name) : undefined))
  }

  @IpcInvoke('add')
  async add(e: ModelChat): Promise<ModelChat> {
    const res = await orm.insert(modelChat).values(e).returning()
    if (res.length > 0) {
      return res[0]
    } else {
      throw new Error('添加失败')
    }
  }

  @IpcInvoke('editByMark')
  async editById(e: ModelChat): Promise<ModelChat> {
    const res = await orm.update(modelChat).set(e).where(eq(modelChat.mark, e.mark)).returning()
    if (res.length > 0) {
      return res[0]
    } else {
      throw new Error('编辑失败')
    }
  }

  @IpcInvoke('deleteByMark')
  async deleteById(mark: string): Promise<number> {
    const res = await orm
      .delete(modelChat)
      .where(eq(modelChat.mark, mark))
      .returning({ mark: modelChat.mark })
    return res.length
  }

  @IpcInvoke('deleteByMarks')
  async deleteByIds(marks: string[]): Promise<number> {
    const res = await orm
      .delete(modelChat)
      .where(inArray(modelChat.mark, marks))
      .returning({ mark: modelChat.mark })
    return res.length
  }
}
